package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.Article;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;

/**
 * @author shkstart
 * 根据文章ID查询作者详情
 * @create 2023-01-12-17:28
 */
@WebServlet("/getuserbyaid")
public class GetUserById extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知参数来自GetUserById";
        UserInfo userInfo = new UserInfo();
        //1.接收前端传递的参数并进行非空校验
        String aidstr = req.getParameter("aid");
        if (!StrUtil.isBlank(aidstr)) {
            int aid = Integer.valueOf(aidstr);
            if(aid>0){
                //2.1得到Connection
                Connection connection = DBUtils.getConnection();
                //2.2sql和执行器
                String sql = "select * from userinfo where uid = ( select uid from article where aid = ? )";//查询username
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,aid);
                //得到结果集
                ResultSet resultSet = statement.executeQuery();
                //这里要进行判空,给对象赋值
                if(resultSet.next()){
                    userInfo.setUsername(resultSet.getString("username"));
                    userInfo.setImg (resultSet.getString("img"));
                    userInfo.setUid(resultSet.getInt("uid"));
                }
                String sql2 = "select count(*) as acount from article where uid = (select uid from article where aid = ?)";
                PreparedStatement statement2 = connection.prepareStatement(sql2);
                statement2.setInt(1,aid);
                ResultSet resultSet2 = statement2.executeQuery();
                if(resultSet2.next()){
                    userInfo.setAcount(resultSet2.getInt("acount"));
                }
                msg = "成功抵达GetUserById";
                //关闭资源
                DBUtils.close(resultSet2,statement2,null);
                DBUtils.close(resultSet,statement,connection);
            }else{
                msg = "错误的aid";
            }
        }else {
            msg="错误的参数";
        }

//        3.将结果返回给前端
        resp.setContentType(AppVar.RESP_JSON_UTF8);
        resp.getWriter().println(
                JSONUtil.toJsonStr(
                        ResultUtils.toResult(200,userInfo,msg)
                )
        );

    }
}
